package com.usefullc.user.service;

import com.usefullc.common.enums.CheckCodeTypeEnum;
import com.usefullc.system.service.AbstractService;
import com.usefullc.user.utils.WeChatUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author: Sampson
 * @date: 11/19/23 4:29 PM
 */
@Service
public class WeixinService extends AbstractService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public String checkToken(HttpServletRequest request) {
        logger.info("checkToken start");
        if (StringUtils.isNotBlank(request.getParameter("signature"))) {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            logger.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
            if (WeChatUtils.checkSignature(signature, timestamp, nonce)) {
                logger.info("checkToken success", echostr);
                return echostr;
            }
        }
        return "check failed";
    }

    public String autoReply(HttpServletRequest request) {
        Map<String, String> requestMap = null;
        try {
            // 调用parseXml方法解析请求消息
            requestMap = WeChatUtils.parseXml(request);
            // 消息类型
            String msgType = requestMap.get("MsgType");
            // xml格式的消息数据
            String respXml = null;
            String mes = requestMap.get("Content");
            // 文本消息
            if ("text".equals(msgType) && mes.indexOf("验证码") >= 0) {
                String code = RandomStringUtils.random(4, false, true);
                respXml = WeChatUtils.sendTextMsg(requestMap, code);
                String openid = requestMap.get("FromUserName");
                CheckCodeTypeEnum checkCodeTypeEnum = CheckCodeTypeEnum.getByCode(CheckCodeTypeEnum.WOA_LOGIN.getCode());
                String cacheKey = StringUtils.join(new Object[]{checkCodeTypeEnum.getCacheKey(), code}, "_");

                String cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);
                if (StringUtils.isNotEmpty(cacheValue)) {  //存在则重新生成,暂时一次
                    logger.info("re generate code,old code={}", code);
                    code = RandomStringUtils.random(4, false, true);
                }
                logger.info("checkCodeKey={},code={},openid={}", cacheKey, code, openid);
                stringRedisTemplate.opsForValue().set(cacheKey, openid, checkCodeTypeEnum.getExpireTime(), checkCodeTypeEnum.getTimeUnit());

            } else if ("text".equals(msgType) && mes.indexOf("0") >= 0) {
                String url = "https://mmbiz.qpic.cn/mmbiz_jpg/9B7wiawVcOw4ib7AFsR4X3Edh3pgydJSId6WGfnvOXaQvViaeicZg4ve7OQgAtdXs6HXh7FW54WiafS9w5YZFmWicNqA/0?wx_fmt=jpeg&from=appmsg";
                String mediaId = "Ikm0CJYuMcid6D5zk2CN-pilp3OlOeWdlUfbF5BfN8FXO82IUQ5xPUJlqed0Ldyi";
                respXml = WeChatUtils.sendImgMsg(requestMap, url, mediaId);

            } else {
                respXml = WeChatUtils.sendTextMsg(requestMap, "您输入的不正确，请重新输入\n如有疑问请回复0加微信咨询");
            }
            return respXml;

        } catch (Exception e) {
            logger.error("auto reply error", e);
            return WeChatUtils.sendTextMsg(requestMap, "您输入的不正确，请重新输入\n如有疑问请回复0加微信咨询");


        }
    }


}
